// component/ui/z-dropdowns/z-dropdowns.js
import {
  _toArray
} from '../common/utils';
const path = '../z-dropdown/z-dropdown'
Component({
  relations: {
    [path]: {
      type: 'descendant',
      linked: function (target) {
        this.updateChild(target)
        this.updateTabs()
      },
      linkChanged: function (target) {},
      unlinked: function (target) {}
    },
  },

  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/,
  },

  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: [String, Number],
      observer(val) {
        this.updateChildren(val)
        this.updateTabs()
      },
    },
    swipeThreshold: {
      type: Number,
      value: 5,
      observer(value) {
        this.setData({
          scrollable: this.children.length > value,
        });
      },
    },
    border: {
      type: Boolean,
      value: false,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabs: [],
    current: '',
    scrollable: false,
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'children', {
        get: () => this.getRelationNodes(path) || [],
      });
    },
    attached() {},
    detached() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    updateTabs() {
      const {
        children = [],
          data
      } = this;
      this.setData({
        tabs: children.map((child) => child.data),
        scrollable: children.length > data.swipeThreshold,
      });
    },
    onClick(e) {
      const {
        name,
        index
      } = e.currentTarget.dataset;
      this.toggle(String(name ? name : index))
    },
    updateChild(child) {
      child.updateActive()
    },
    updateChildren(val) {
      this.setData({
        current: String(val),
      });
      (this.children || []).forEach((child) => child.updateActive())
    },
    toggle(active) {
      const {
        current
      } = this.data
      this.updateChildren(active === current ? '' : active)
      this.updateTabs()
      this.triggerEvent('change', active === current ? '' : active)
    },
    onClear() {
      (this.children || []).forEach((child) => child.onClear());
      this.updateTabs()
    },
  }
})